package d0524_io案例;

public class equals函数与hashCode函数的关系 {
	public static void main(String[] args) {
		String str="卢本伟";
		String str2="卢本伟";
		System.out.println("str的hashCode:"+str.hashCode());
		System.out.println("str2的hashCode:"+str2.hashCode());
		System.out.println(str.equals(str2));
		System.out.println("======将str2的值改变==========");
		str2+="牛逼";
		System.out.println("str的hashCode:"+str.hashCode());
		System.out.println("str2的hashCode:"+str2.hashCode()); //此时str2的hashCode发生了变化;
		System.out.println(str.equals(str2));
		System.out.println("======将str2的值改回来==========");
		str2="卢本伟";
		System.out.println("str的hashCode:"+str.hashCode());
		System.out.println("str2的hashCode:"+str2.hashCode()); //此时str2的hashCode发生了变化;
		System.out.println(str.equals(str2));
		System.out.println("======将str和str2的值都改变后都在改回来==========");
		str="伞兵一号";
		str2="伞兵一号";
		str="卢本伟";
		str2="卢本伟";
		System.out.println(str.hashCode());
		System.out.println(str2.hashCode());
		
		//如果内存中有个地方储存有一个"卢本伟"的字符串,那么再次给str2赋值"卢本伟时",系统会自动指向原来
		//的str中的卢本伟1.equal()相等的两个对象他们的hashCode()肯定相等，也就是用equal()对比是绝对可靠的。
	}
}


class A {
	private int age;
	private String name;
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		A other = (A) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
	
}



